<?php

extract(extractPost(), EXTR_PREFIX_ALL, 'c');
//WIP
if ( isset($c_log_wip) && isset($c_card_id) )
{
	$card = R::load('card', $c_card_id);
	if ( $card->id == 0 ) jsonErrorDie('Card does not exist');
	R::store($card);

	logCardMoveWIP($card);
	jsonSuccessDie('message', 'Violation has been logged');
}

if ( isset($c_user_id) && isset($c_card_id) && isset($c_column_id))
{ //isset($c_board_id) && isset($c_user_id) && isset($c_card_id) && isset($c_project_id) && isset($c_direction)){
	//inits
	$user = R::load('user', $c_user_id);
	$new_col = R::load('column', $c_column_id);
	if ( $user->id == 0 ) jsonErrorDie('User does not exist');
	$card = R::load('card', $c_card_id);
	if ( $card->id == 0 ) jsonErrorDie('Card does not exist');
	if ( $new_col->id == 0 ) jsonErrorDie('Column does not exist');
	$previous = null;
	$column = $card->column; //R::load('column', $c_column_id); if($column->id == 0) jsonErrorDie('Column does not exist');
	if ( $column->id == 0 )
	{
		jsonErrorDie('Card is not yet in any column');
	}
	//$board = $column->board; //R::load('board', $c_board_id); if($board->id == 0) jsonErrorDie('Board does not exist');
	$group = R::load('group', $card->project->dev_group);
	if ( $group->id == 0 )
	{
		jsonErrorDie("Couldn't get group for this project");
	}

	//uporabnik prestavlja samo kartice, ki pripadajo njegovemu projektu.
	//pogledam ce uporabnik pripada skupini in ta skupina tabli
	if ( ! ((isInBeans($user->id, $group->sharedUserList) && in_array($user->id, json_decode($group->developers))) ||
		$group->kanbanMaster == $user->id || $group->product_owner == $user->id)
	)
	{
		jsonErrorDie("This card doesn't belong to user project." . $group->product_owner . " u" . $user->id);
	}

	$card->column = $new_col;
	R::store($card);

	if ( $column->id)
		logCardMove($card, $new_col, $column);
	//LOG a move

	//TODO prestavljanje kartice, ki predstavlja zavrnjeno zgodbo (kartico lahko prestavi samo Product Owner, kartica se lahko prestavi v stolpec s karticami z najvišjo prioriteto ali v kateregakoli levo od njega; če pri tem pride do kršitve omejitve WIP, se ta kršitev zabeleži; tip/barva kartice se spremeni).
	//KDAJ JE ZGODBA ZAVRNJENA?

	jsonSuccessDie('message', 'Card was moved.');
}

jsonErrorDie("Wrong parameters for card_id, user_id or direction.");
